<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/jsp/common.jsp"%>
<!DOCTYPE html>
<html>
<head>
	<base href="<%=basePath%>">
	<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
	<title>当前活动</title>
	
	<link href="bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
	<link href="css/bootstrap-table.min.css" rel="stylesheet">
	<link href="css/bootstrap-datetimepicker.min.css" rel="stylesheet">
	
	<script src="jquery/2.1.1/jquery.min.js"></script>
	<script src="bootstrap/3.2.0/js/bootstrap.min.js"></script>
	<script src="js/bootstrap-table.min.js"></script>
	<script src="js/bootstrap-table-locale-all.min.js"></script>
	<script src="layer/layer.js"></script>
	<script src="js/bootstrap-datetimepicker.min.js"></script>
	<script src="js/bootstrap-datetimepicker.fr.js"></script>
	<script src="js/bootstrap-datetimepicker.zh-CN.js"></script>
	<style type="text/css">
		.navbar-static-top {
			background-color: #212121;
			margin-bottom: 5px;
		}
		#logo {
			/* background: url('toIndexPage') no-repeat 20px 20px; */
			display: inline-block;
			vertical-align: middle;
			padding-left: 20px;
			color: #fff;
			font: oblique bold 20px/20px arial,sans-serif;
		}
	</style>
</head>
<body>
	<%@ include file="/WEB-INF/jsp/menu_top.jsp"%>
    <div class="container-fluid">
        <div id="main-content" class="row">
            <div class="col-md-12 page all_user active" >
            	<div class="col-md-12">
            		<div id="userToolbar" class="">
						<button id="addUser" type="button" class="btn btn-default">
							<span class="glyphicon glyphicon-plus-sign" ></span>添加
						</button>
						<button id="editUser" type="button" class="btn btn-default" disabled="disabled" >
							<span class="glyphicon glyphicon-pencil" ></span>修改
						</button>
						<button id="removeUser" type="button" class="btn btn-default" disabled="disabled" >
							<span class="glyphicon glyphicon-remove" ></span>删除
						</button>
						<label for="user_userName">用户名：</label>
						<input id="user_userName" type="text" value="" class="input-sm">
						<label for="user_nickName">昵称：</label>
						<input id="user_nickName" type="text" value="" class="input-sm">
						<button id="searchUser" type="button" class="btn btn-default">
							<span class="glyphicon glyphicon-search" ></span>搜索
						</button>
					</div>
					<table id="userTable" class="table table-bordered table-striped table-hover"></table>
				</div>
            </div>
        </div>
    </div>
<!-- 模态框（Modal） -->
<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                	<span class="glyphicon glyphicon-remove" ></span>
                </button>
                <h4 class="modal-title" id="addUserTitle">添加账号</h4>
            </div>
            <div class="modal-body">
				<form id="addUserForm">
					<input type="hidden" name="id" value="">
					<input type="text" name="userName" class="form-control" placeholder="用户名" required autofocus> 
					<input type="password" name="password" class="form-control" placeholder="密码">
					<input type="text" name="nickName" class="form-control" placeholder="昵称" required>
					<select name="role.id" class="form-control">
					</select>
					<select name="status" class="form-control">
						<option value="0">无效</option>
						<option value="1">正常</option>
					</select>
				</form>
			</div>
            <div class="modal-footer">
                <button id="saveUser" type="button" class="btn btn-primary">
                	<span class="glyphicon glyphicon-ok" ></span> 保存
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>
</body>
<script type="text/javascript">
	var userTable = $('#userTable');
	var addUser = $('#addUser');
	var saveUser = $('#saveUser');
	var removeUser = $('#removeUser');
	var editUser = $('#editUser');
	var searchUser = $('#searchUser');
	var addUserForm = $("#addUserForm");
	var addUserModal = $("#addUserModal");
	
	var curDate;
	var curActivityType;

	$(function() {
		
		//初始化userTable
		var userTable = new userTableInit();
		userTable.Init();
		
		//用户类型初始化
		initUserType();
		
		//initDateTimePicker();
	});
	
	function initDateTimePicker(){
		$('.activity_time').datetimepicker({
	        format:"yyyy-mm-dd hh:ii:ss",
	        weekStart: 1,
	        todayBtn: true,
	        autoclose: 1,
	        todayHighlight: 1,
	        showMeridian: 1,
	        language: 'zh-CN'
	    });
		$('.activity_date').datetimepicker({
	        format:"yyyy-mm-dd",
	        weekStart: 1,
	        autoclose: 0,
	        todayHighlight: 1,
	        minView : 2,
	        maxView : 4,
	        language: 'zh-CN'
	    });
	}
	function initUserType(){
		$.ajax({
            type: "post",
            url: 'roleList',
            success: function (data) {
            	$.each(data,function(key, value){
					addUserForm.find("select[name='role.id']").append("<option value="+value.id+">"+value.roleName+"</option>");
           		});
            }
        });
	}
	window.operateEvents = {
	    'click .validUser': function (e, value, row, index) {
	        $.ajax({
	            type: "post",
	            data: {status:1,id:row.id},
	            url: 'updateUserStatus',
	            success: function (data) {
	                layer.msg('修改成功！', {icon: 1});
	                userTable.bootstrapTable('refresh');
	            }
	        });
	    },
	    'click .invalidUser': function (e, value, row, index) {
	    	//alert(JSON.stringify(row));
	        $.ajax({
	            type: "post",
	            data: {status:0,id:row.id},
	            url: 'updateUserStatus',
	            success: function (data) {
	                layer.msg('修改成功！', {icon: 1});
	                userTable.bootstrapTable('refresh');
	            }
	        });
	    },
	    'click .removeUser': function (e, value, row, index) {
	        $.ajax({
	            type: "post",
	            data: {ids:row.id},
	            url: 'removeUser',
	            success: function (data) {
	            	layer.msg('删除成功！', {time: 2000,icon: 1});
	            	userTable.bootstrapTable('refresh');
	            }
	        });
	    }
	};

	
	var userTableInit = function() {
		var userTableObj = new Object();
		userTableObj.Init = function() {
			userTable.bootstrapTable('destroy');//先销毁表格
			userTable.bootstrapTable({
				url : 'userList', //请求后台的URL（*）
				method : 'post', //请求方式（*）
				contentType: "application/x-www-form-urlencoded",//果然是必须的（*）
				toolbar : '#userToolbar', //工具按钮用哪个容器
				buttonsAlign: "right",//按钮对齐方式
                toolbarAlign: "left",//工具栏对齐方式
				striped : true, //是否显示行间隔色
				//search: true,  //是否启用查询  
				//searchOnEnterKey : true,//是否回车查询
				//strictSearch : false,
            	showColumns: true,  //显示下拉框勾选要显示的列  
            	showRefresh: true,  //显示刷新按钮  
				cache : false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
				pagination : true, //是否显示分页（*）
				//sortable : true, //是否启用排序
				//sortName : 'userName',
				//sortOrder : "asc", //排序方式
				sidePagination : "server", //分页方式：client客户端分页，server服务端分页（*）
				pageNumber : 1, //初始化加载第一页，默认第一页
				pageSize : 5, //每页的记录行数（*）
				pageList : [ 5, 10, 50, 100 ], //可供选择的每页的行数（*）
				clickToSelect : true, //是否启用点击选中行
				//height : userTableObj.getHeight(), //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
				//width : userTableObj.getWidth(),
				uniqueId : "id", //每一行的唯一标识，一般为主键列
				locale : 'zh-CN',//设置时区（*）
				queryParams : userTableObj.queryParams,//传递参数（*）
				queryParamsType : '',//queryParamsType : 'limit'时，分页参数改用limit和offset（*）
				columns : [ {
					field : 'selectStatus',
					//radio : true
					checkbox : true
				}, {	
					field : 'userName',
					title : '用户名'
				}, {
					field : 'nickName',
					title : '昵称'
				}, {
					field : 'role.roleName',
					title : '账号类型'
				}, {
					field : 'status',
					title : '状态',
					formatter:function(value,row,index){
						if (row.status==1) {
							return '正常';
						}else{
							return '无效';
						}
					}
				}, {
					field : 'createdTime',
					title : '创建时间'
				}, {
					field : 'updatedTime',
					title : '最后修改时间'
				}, {
			        field: 'operation',
			        title: '操作',
			        formatter:function(value,row,index){
			            //var removeUser = '<a class = "removeUser" href="javascript:void(0)"><i class="glyphicon glyphicon-remove"></i></a>';
			            var operation ;
			            if (row.status==1) {
			            	operation = '<a class = "invalidUser" href="javascript:void(0)">反审</a>';
						}else{
							operation = '<a class = "validUser" href="javascript:void(0)">审核</a>';
						}
			            return operation;
			        },
			        events: 'operateEvents'
				}, ],
				responseHandler : function(page) {
					var user = {};
					user.rows = page.content;
					user.total = page.totalElements;
					user.totalPages = page.totalPages;
					return user;
				},
			});
			// 有时候 footer 渲染异常
			setTimeout(function () {
				userTable.bootstrapTable('resetView');
			}, 200);
			//table 勾选，取消勾选，全选，取消全选 事件
			userTable.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', 
				function() {
					removeUser.prop('disabled', !userTable.bootstrapTable('getSelections').length);
					editUser.prop('disabled', userTable.bootstrapTable('getSelections').length!=1);
			});
			//删除按钮
			removeUser.click(function() {
				layer.confirm('确定要删除所选数据？', {icon: 3, title:'提示'}, function(index){
					var ids = userTableObj.getIdSelections();
		            $.ajax({  
		                url:'removeUser',  
		                //traditional: true,  //阻止深度序列化,向后台传送数组 ;或直接拼接字符串
		                //data:{ids:ids}, 
		                data:"ids="+ids.join(","),
		                contentType:'application/json',  
		                success:function(data){  
		                    if(data.count){  
		                        layer.msg(data.message,{time: 1000,icon:1});  
		                    }else{  
		                        layer.msg(data.message,{time: 1000,icon:2});  
		                    }
		                    userTable.bootstrapTable('refresh');
		                    removeUser.prop('disabled', true);
		                    editUser.prop('disabled', true);
		                },
		                error:function(XMLHttpRequest, textStatus, errorThrown) {
		                    layer.msg(textStatus+';'+errorThrown,{time: 1000,icon:2}); 
		                }
		            });
					layer.close(index);
					
				},function(index){layer.close(index);});
			});
			//搜索按钮
			searchUser.click(function() {
				//userTable.bootstrapTable({pageNumber:1});//方案1，不起作用
				//alert(JSON.stringify(userTable));
				//userTable.bootstrapTable('refresh');
				var userTable = new userTableInit();//方案2
				userTable.Init();
			});
			//修改按钮
			editUser.click(function() {
				addUserModal.modal("show");
				addUserForm[0].reset();
				$("#addUserTitle").html("修改账号");
				var user = userTable.bootstrapTable('getSelections')[0];
				addUserForm.find("input[name='id']").val(user.id);
				addUserForm.find("input[name='userName']").val(user.userName);
				addUserForm.find("input[name='nickName']").val(user.nickName);
				addUserForm.find("select[name='status']").val(user.status);
				addUserForm.find("select[name='role.id']").val(user.role.id);
			});
			//添加按钮
			addUser.click(function() {
				addUserModal.modal("show");
				addUserForm[0].reset();//reset对hidden无效
				addUserForm.find("input[name='id']").val('');//清除hidden值
				$("#addUserTitle").html("添加账号");
			});
			//保存按钮
			saveUser.click(function() {
				if (addUserForm.find("input[name='userName']").val()=='') {
					layer.msg('用户名不能为空');
					return;
				}
				if (addUserForm.find("input[name='password']").val()=='') {
					layer.msg('密码不能为空');
					return;
				}
				
				var params = $("#addUserForm").serialize();
				params = decodeURIComponent(params,true);
				//alert(JSON.stringify(params));
				$.ajax({  
	                url:'saveUser',  
	                data : params,
	                type: "POST",
	                //contentType:'application/json',  
	                success:function(data){
	                    if(data.count){  
	                        layer.msg(data.message,{time: 1000,icon:1});  
		                    userTable.bootstrapTable('refresh');
		                    addUserModal.modal("hide");
	                    }else{  
	                        layer.msg(data.message,{time: 1000,icon:2});  
	                    }
	                },
	                error:function(XMLHttpRequest, textStatus, errorThrown) {
	                    layer.msg(textStatus+';'+errorThrown,{time: 1000,icon:2});
	                }
	            });
			});
			//窗口尺寸变动
			$(window).resize(function() {
				userTable.bootstrapTable('resetView', {
					width : userTableObj.getWidth(),
					height : userTableObj.getHeight()
				});
			});

		};

		//得到查询的参数
		userTableObj.queryParams = function(params) {
			params.userName = $("#user_userName").val();
			params.nickName = $("#user_nickName").val();
			//params.pageNumber = params.pageNumber;
			return params;
		};
		userTableObj.getHeight = function() {
			return $(window).height() - 50;
		};
		userTableObj.getWidth = function() {
			return $(window).width() - 50;
		};
		userTableObj.getIdSelections = function() {
			return $.map(userTable.bootstrapTable('getSelections'), function (row) {
			    return row.id;
			});
		};

		return userTableObj;
	};

</script>
</html>
